//test_array.js
var memory;
var imported = {
    memory: new WebAssembly.Memory({ initial: 1 }),
    abort: function (a, b, c, d) { console.log("abort"); },
    sin: Math.sin,
    "performance.now": () => performance.now()  // 提供 performance.now 的替代实现
};

imported["console.log"] = function (a) {
    console.log(new Uint8Array(memory.buffer, a, 1));
}

function test(file, func, ...args) {
    const bytes = readbuffer(file);
    const mod = new WebAssembly.Module(bytes);
    const instance = new WebAssembly.Instance(mod, { env: imported });
    memory = instance.exports.memory;

    const startTime1 = performance.now();
    const outPtr = instance.exports[func](...args);
    const endTime1 = performance.now();
    console.log(`calculate time: ${(endTime1 - startTime1)} ms`);
    /*
    if (func === "withInputNoOutput") {
        // 处理 withInputNoOutput 的返回值
        const ans = new Uint32Array(memory.buffer, outPtr, 1)[0];
        console.log(`Last Element from Input Array (No Output): ${ans}`);
    } else 
    */

    if (outPtr !== undefined) {
        const startTime2 = performance.now();
        const Output = new Uint32Array(memory.buffer, outPtr, args[0]);

        const endTime2 = performance.now();
        console.log(Output[args[0]-1]);
        console.log(`calculate time: ${(endTime2 - startTime2)} ms`);
    }
}

// 调用四个函数
const size = 20000000;
const inputArray = new Uint32Array(size);  // 模拟输入数组
// 为输入数组赋值，从1到size
for (let i = 0; i < size; i++) {
    inputArray[i] = i + 1;
}


filepath ="build/test_array.wasm"
//test(filepath , "baselineTest", size);
test(filepath , "noInputWithOutput", size);
//test(filepath , "withInputNoOutput", inputArray, size);
//test(filepath , "withInputAndOutput", inputArray, size);
